package com.xiaobai.netease_news.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.ImageView;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Intellij IDEA
 * Project: NeihanDuanzi
 * Author: Jack
 * Email: jackfangqi1314@gmail.com/jackfangqi@163.com
 * Date: 2015/5/30
 */

/**
 * 图片下载器
 */
public class ImageLoadTask extends AsyncTask<String, Void, Bitmap> {
    private ImageView imageView;
    private String url;

    public ImageLoadTask(ImageView imageView) {
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(String... params) {

        Bitmap bitmap = null;
        if (params != null && params.length > 0) {
            // 作为网址请求，同时还进行ImageView tag的检查
            url = params[0];

            // TODO 检测文件缓存
            String externalStorageState = Environment.getExternalStorageState();
            // 找到的缓存的文件
            File targetFile = null;
            if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
                // 存储卡根目录
                File storageDirectory = Environment.getExternalStorageDirectory();
                // 对应的文件目录地址 /mnt/sdcard/.neihan/images
                File imageCache = new File(storageDirectory, ".neihan/images");
                boolean b = true;
                // 递归的创建指定的文件目录，确保创建成功
                if (!imageCache.exists())
                    b = imageCache.mkdirs();
                if (b) {
                    // 文件的查找，根据url来查找

                    // 进行映射
                    String fileName = CacheUtil.md5(url);
                    targetFile = new File(imageCache, fileName);
                }
            }

            if (targetFile == null || !targetFile.exists()) {
                try {
                    URL u = new URL(url);
                    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setReadTimeout(5000);
                    connection.setRequestProperty("connection", "keep-alive");
                    connection.connect();
                    // 获取输入流
                    InputStream inputStream = connection.getInputStream();
                    // 读取图片数据到字节数组，便于后续的文件缓存操作
                    byte[] data = StreamUtil.readStream(inputStream);
                    inputStream.close();
                    connection.disconnect();    // 断开连接

                    // TODO 要这对图片进行本地文件缓存
                    if (targetFile != null) {
                        // 能够获取到SD卡的路径文件对象，但是文件不存在
                        boolean b = targetFile.createNewFile();
                        // 创建文件成功
                        if (b) {
                            FileOutputStream fileOutputStream = null;
                            try {
                                fileOutputStream = new FileOutputStream(targetFile);
                                fileOutputStream.write(data);
                            } catch (IOException e) {
                                e.printStackTrace();
                            } finally {
                                if (fileOutputStream != null) {
                                    fileOutputStream.close();
                                }
                            }
                        }
                    }

                    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    //当图像创建成功，bitmap会包含一份图像的数据
                    // data也是一份图像的数据，需要释放
                    data = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                // targetFile存在
                bitmap = BitmapFactory.decodeFile(targetFile.getAbsolutePath());
            }
        }

        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (bitmap != null) {
            if (imageView != null) {
                Object tag = imageView.getTag();
                if (tag != null && tag instanceof String) {
                    String s = (String) tag;
                    if (s.equals(url))
                        imageView.setImageBitmap(bitmap);
                }
            }
        }
    }
}
